/*
 * This file is part of Plop Messenger.
 *
 * Plop Messenger is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  Plop Messenger is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Plop Messenger.  If not, see <http://www.gnu.org/licenses/>.
 */
package pm.ui;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JTextField;

public class HistoryJTextField extends JTextField implements KeyListener {
	private static final long serialVersionUID = 1L;
	private int current = 0;
	private List<String> history = new ArrayList<String>();
	private List<HistoryJTextFieldListener> listeners = new ArrayList<HistoryJTextFieldListener>();

	private int maxHistory;

	public HistoryJTextField(int maxHistory) {
		this.maxHistory = maxHistory;
		this.addKeyListener(this);
	}

	public void addListener(HistoryJTextFieldListener e) {
		listeners.add(e);
	}

	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getSource() == this) {
			if (e.getKeyCode() == KeyEvent.VK_UP) {
				current--;
				if (current < 0)
					current = 0;
				if (history.size() > 0)
					this.setText(history.get(current));
			} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
				current++;
				if (current > history.size())
					current = history.size();
				if (current == history.size())
					this.setText("");
				else if (history.size() > 0)
					this.setText(history.get(current));
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		if (e.getSource() == this) {
			if (e.getKeyChar() == KeyEvent.VK_ENTER) {
				if (this.getText().length() > 0) {
					history.add(this.getText());
					if (history.size() > maxHistory && maxHistory >= 0)
						history.remove(0);
					current = history.size();
					String text = this.getText();
					for (HistoryJTextFieldListener l : listeners) {
						l.newText(this, text);
					}
					this.setText("");
				}
			}
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {
	}

	public void removeListener(HistoryJTextFieldListener e) {
		listeners.remove(e);
	}

}
